/*********************************************************************************
 * File Name: ImageUtil.java
 * Package Name: com.sensorfriendly.util
 * 
 * Purpose:
 * This class defines the functions to resize the images to fit the
 * defined size so as to not get squashed or stretched if the aspect
 * ratios or dpi dont match
 *  
 *********************************************************************************/
package com.sensorfriendly.util;

import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageUtil {
	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}
	
	/**
	 * Load image from file path
	 * @param path path to the image file
	 * @param screenWidth desired width
	 * @param screenHeight desired height
	 * @return
	 */
	public static Bitmap decodeSampledBitmapFromPath(String path, int screenWidth, int screenHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);
		int reqWidth=(int)(screenWidth*0.6);
		int reqHeight =(int)(screenHeight*0.45);
		
		
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		Bitmap image = BitmapFactory.decodeFile(path, options);
		
		
		if(screenWidth > screenHeight){
			Bitmap scaledMap = Bitmap.createScaledBitmap(image, (int) (screenWidth*0.5), (int) (screenHeight*0.5), false);
			image.recycle();
			return scaledMap;
		}
		return image; 
	}
	
	/**
	 * load file from input stream
	 * @param is image file input stream
	 * @param screenWidth desired width
	 * @param screenHeight desired height
	 * @return
	 */
	public static Bitmap decodeSampledBitmapFromStream(InputStream is , int screenWidth, int screenHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(is, null,options);
		
		int reqWidth =(int)(screenWidth*0.8);
		int reqHeight =(int)(screenHeight*0.8);
		
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
		
		
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeStream(is,null, options);
	}
}
